package net.jmchilton.spring.collect.spec;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

/**
 * The main method of this class is responsible for taking in
 * an expanded namespace XML file and producing runtime artifacts
 * required for this extension to work.
 * 
 * schema.xsd - 
 *   This will contain an XSD description of elements corresponding
 * to the input namespace. This is required for Spring to validate
 * user XML files and may likewise be useful for relevant tooling.  
 * 
 * static-factories.properties -
 *   XML elements product objects at runtime by reflectively calling
 * static methods, this file describes the mapping of elements to 
 * methods required to do this.
 * 
 * @author John Chilton
 */
public class SchemaExporter {

  /**
   * Actually performs the tasks described in class documentation.
   * 
   * @param args Input arguments, see build.xml for example of how to call
   *   this method.
   */
  public static void main(final String[] args) {
    try { 
      System.out.println("Loading namespace");
      final Spec spec = new Spec(new File(args[0], args[1] + ".xml"));

      System.out.println("Verifing namespace " + spec.getNamespace().getUri());
      Verifier.verify(spec.getNamespace());

      final String packagePath = args[2];        
      final String schemaPath = packagePath + "schema.xsd";
      System.out.println("Writing schema definition to file " + packagePath + "schema.xsd");

      // Load schema outline and replace relevant pieces from loaded spec,
      String template = IOUtils.toString(SchemaExporter.class.getResourceAsStream("schema-outline.xml"));
      template = template.replace("NAMESPACE", spec.getNamespace().getUri());
      template = template.replace("CONTENT", spec.getContents());
      FileUtils.writeStringToFile(new File(schemaPath), template);

      // Write out static-factories.properties, the runtime infrastructure
      // requires this to map elements to the correct static factories.
      final String factoryPropertiesPath = packagePath + "static-factories.properties";
      System.out.println("Writing factory properties to file " + factoryPropertiesPath);
      FileUtils.writeStringToFile(new File(factoryPropertiesPath), spec.getPropertiesContents());
    } catch(IOException e) {
      throw new RuntimeException(e);
    }
  }

}
